/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ui.gui.documents.actions;

import java.awt.event.ActionEvent;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.swing.AbstractAction;

import parser.AltaRicaParseModel;
import parser.AltaRicaParser;
import parser.AltaRicaParseNode.CycleDetectionException;

import ui.gui.actions.OpenFileAction;
import ui.gui.documents.AbstractDocument;
import ui.gui.documents.AltaricaCodeEditor;
import ui.gui.documents.EditorAction;
import common.AltaRicaModel;

/**
 *
 * @author stephane
 */
public class ActionFormatCode extends EditorAction {

    private static final long serialVersionUID = 1L;

    public ActionFormatCode(AbstractDocument document) {
        super("Format current document", document);
        putValue(AbstractAction.SMALL_ICON, new javax.swing.ImageIcon(OpenFileAction.class.getResource("/resources/formatcode.png")));
        putValue(AbstractAction.SHORT_DESCRIPTION, "Format code");
    }

    @Override 
    public void actionPerformed(ActionEvent e) {
        if (getDocument() != null && getDocument() instanceof AltaricaCodeEditor) {
            AltaricaCodeEditor editor = (AltaricaCodeEditor) getDocument();   
        	InputStream is = new ByteArrayInputStream(editor.getText().getBytes());
            AltaRicaParseModel pmodel = AltaRicaParser.parseModel(editor.getFileName(), is);
            if (pmodel != null && !pmodel.getParseError()) {
	            try
	            {
		            AltaRicaModel model = AltaRicaModel.compileFromAST(pmodel, false);
		            if (model != null) {
		               
		                editor.getEditorObject().setText(model.string());
		            }
	            }
	            catch (CycleDetectionException exception) {
	            	System.out.println(exception.getMessage());
	            }
            }
        }
    }
}
